package com.zyh.shortlick.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.shortlick.admin.common.constant.RedisCacheConstant;
import com.zyh.shortlick.admin.common.convention.exception.ClientException;
import com.zyh.shortlick.admin.common.convention.exception.ServiceException;
import com.zyh.shortlick.admin.common.enums.UserErrorCodeEnum;
import com.zyh.shortlick.admin.dao.entity.UserDO;
import com.zyh.shortlick.admin.dao.mapper.UserMapper;
import com.zyh.shortlick.admin.dto.req.UserLoginReqDTO;
import com.zyh.shortlick.admin.dto.req.UserRegisterReqDTO;
import com.zyh.shortlick.admin.dto.req.UserUpdateReqDTO;
import com.zyh.shortlick.admin.dto.resp.UserLoginRespDTO;
import com.zyh.shortlick.admin.dto.resp.UserRespDto;
import com.zyh.shortlick.admin.service.GroupService;
import com.zyh.shortlick.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.zyh.shortlick.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static com.zyh.shortlick.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate redisTemplate;
    private final GroupService groupService;

    @Override
    public UserRespDto getUserByUserName(String username) {
        LambdaQueryWrapper<UserDO> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDO::getUsername, username);
        UserDO one = this.getOne(lqw);
        if (one == null) {
            throw new ServiceException(UserErrorCodeEnum.USER_NULL);
        }
        UserRespDto result = new UserRespDto();
//        字段多的类拷贝到字段少的类
        BeanUtil.copyProperties(one, result);
        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
//        LambdaQueryWrapper<UserDO> lqw=new LambdaQueryWrapper<>();
//        lqw.eq(UserDO::getUsername,username);
//        UserDO user = this.getOne(lqw);
//        if (user==null){
//            return false;
//        }
//        return true;
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    //    如果是用一个用户名同时进行大量注册，用redisson的分布式锁可以确保
//    同一个用户名只能有一个获取到锁，其他的走失败逻辑
//    但如果是用多个用户名同时进行大量注册，就要使用sentinel对接口限流
//    注册用户成功后把username添加到布隆过滤器中
    @Override
    public void register(UserRegisterReqDTO requestParam) {
        String username = requestParam.getUsername();
        Boolean flag = this.hasUsername(username);
        if (!flag) {
            throw new ClientException(USER_NAME_EXIST);
        }
        RLock lock = redissonClient.getLock(RedisCacheConstant.LOCK_USER_REGISTER_KEY + username);
        try {
            if (lock.tryLock()) {
                try {
                    boolean save = this.save(BeanUtil.toBean(requestParam, UserDO.class));
                    if (save == false) {
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                } catch (DuplicateKeyException exception) {
//                    防止布隆过滤器误判，在这里加个保底
                    throw new ClientException(USER_EXIST);
                }
                userRegisterCachePenetrationBloomFilter.add(username);
                groupService.saveGroup(requestParam.getUsername(),"默认分组");
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }
    }


    @Override
    public void update(UserUpdateReqDTO requestParam) {
//        后面还要用gateway判断修改用户信息的是不是登录用户
//        感觉有问题，要是用户名变了还怎么修改
        UserDO userDO = BeanUtil.copyProperties(requestParam, UserDO.class);
        LambdaQueryWrapper<UserDO> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDO::getUsername, requestParam.getUsername());
        this.update(userDO, lqw);
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        LambdaQueryWrapper<UserDO> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO one = this.getOne(lqw);
        if (one == null) {
            throw new ClientException("用户不存在或密码错误");
        }
//      之前那样写，登录之后再次登录会报错
        Map<Object ,Object> hasLoginMap = redisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
//        这里返回的token和下面的uuid是一样的
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }

        String uuid = UUID.randomUUID().toString();
        redisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(one));
        redisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username, String token) {
        return redisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    @Override
    public void logout(String username, String token) {
        Boolean flag = checkLogin(username, token);
        if (flag) {
            redisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        throw new ClientException("用户未登录或token不存在");
    }
}
